import { createApp } from 'vue'
import config from './config'
import Taro from '@tarojs/taro'

import './app.css'

// Define checkToken outside of createApp
async function checkToken() {
  const token = Taro.getStorageSync('token')
  if (!token) {
    Taro.setStorageSync('isLoggedIn', false)
    Taro.showToast({ title: '请先登录', icon: 'none' })
    // 可跳转到登录页
    // Taro.redirectTo({ url: '/pages/login/index' })
    return
  }
  // Validate token
  try {
    const res = await Taro.request({
      url: `${config.apiUrl}/login/secure/checkToken`,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': token
      }
    })
    if (res.data !== 'invalid_token' && res.data !== 'no_token') {
      Taro.setStorageSync('isLoggedIn', true)
    } else {
      Taro.clearStorageSync();
      Taro.setStorageSync('isLoggedIn', false);
      Taro.showToast({ title: '登录已过期，请重新登录', icon: 'none' })
      // Taro.redirectTo({ url: '/pages/login/index' })
    }
  } catch (e) {
    Taro.setStorageSync('isLoggedIn', false)
    Taro.removeStorageSync('token')
    Taro.showToast({ title: '网络异常，请重新登录', icon: 'none' })
  }
}

const App = createApp({
  onLaunch() {
    checkToken()
  },
})

export default App